import 'package:get/get.dart';
import 'package:sinosheets/utils/favorite/isar_product_service.dart';
import 'package:sinosheets/utils/favorite/flash_sale_product_model.dart';
import 'package:sinosheets/utils/favorite/normal_product_model.dart';
import 'package:sinosheets/utils/common_utils/log_util.dart';

class ProductService extends GetxService {
  static final ProductService _instance = ProductService._internal();
  factory ProductService() => _instance;
  ProductService._internal();

  final IsarProductService _isarService = IsarProductService();
  bool _isInitialized = false;

  final RxList<FlashSaleProductModel> _favoriteFlashSaleProducts = <FlashSaleProductModel>[].obs;
  final RxList<NormalProductModel> _favoriteNormalProducts = <NormalProductModel>[].obs;

  List<FlashSaleProductModel> get favoriteFlashSaleProducts => _favoriteFlashSaleProducts;
  List<NormalProductModel> get favoriteNormalProducts => _favoriteNormalProducts;

  Future<void> init() async {
    if (_isInitialized) return;
    try {
      await _isarService.init();
      await loadFavoriteProducts();
      _isInitialized = true;
    } catch (e) {
      LogUtil.e('[ProductService] 初始化失败: $e');
      rethrow;
    }
  }

  bool get isInitialized => _isInitialized;

  Future<void> loadFavoriteProducts() async {
    if (!_isInitialized) return;
    try {
      final flashSale = await _isarService.getFavoriteFlashSaleProducts();
      final normal = await _isarService.getFavoriteNormalProducts();
      _favoriteFlashSaleProducts.assignAll(flashSale);
      _favoriteNormalProducts.assignAll(normal);
    } catch (e) {
      LogUtil.e('[ProductService] 加载收藏商品失败: $e');
    }
  }

  // ==================== FlashSaleProduct 收藏 ====================
  Future<bool> toggleFlashSaleProductFavorite(Map<String, dynamic> productData) async {
    if (!_isInitialized) return false;
    final productId = productData['id']?.toString() ?? '';
    final isFav = await _isarService.isFlashSaleProductFavorite(productId);
    if (isFav) {
      await _isarService.removeFavoriteFlashSaleProduct(productId);
    } else {
      await _isarService.addFavoriteFlashSaleProduct(productData);
    }
    await loadFavoriteProducts();
    return !isFav;
  }

  Future<bool> isFlashSaleProductFavorite(String productId) async {
    if (!_isInitialized) return false;
    return await _isarService.isFlashSaleProductFavorite(productId);
  }

  // ==================== NormalProduct 收藏 ====================
  Future<bool> toggleNormalProductFavorite(Map<String, dynamic> productData) async {
    if (!_isInitialized) return false;
    final productId = productData['id']?.toString() ?? '';
    final isFav = await _isarService.isNormalProductFavorite(productId);
    if (isFav) {
      await _isarService.removeFavoriteNormalProduct(productId);
    } else {
      await _isarService.addFavoriteNormalProduct(productData);
    }
    await loadFavoriteProducts();
    return !isFav;
  }

  Future<bool> isNormalProductFavorite(String productId) async {
    if (!_isInitialized) return false;
    return await _isarService.isNormalProductFavorite(productId);
  }

  // ==================== 通用操作 ====================
  Future<void> clearAllFavorites() async {
    if (!_isInitialized) return;
    await _isarService.clearAllFavorites();
    _favoriteFlashSaleProducts.clear();
    _favoriteNormalProducts.clear();
  }

  Future<void> refreshAllData() async {
    if (!_isInitialized) return;
    await loadFavoriteProducts();
  }

  Map<String, dynamic> exportProductData() {
    return {
      'flashSaleProducts': _favoriteFlashSaleProducts
          .map((p) => {
                'productId': p.productId,
                'inId': p.inId,
                'productName': p.productName,
                'productImage': p.productImage,
                'price': p.price,
                'crossedPrice': p.crossedPrice,
                'symbol': p.symbol,
                'detailUrl': p.detailUrl,
                'category': p.category,
                'createTime': p.createTime.toIso8601String(),
                'updateTime': p.updateTime.toIso8601String(),
              })
          .toList(),
      'normalProducts': _favoriteNormalProducts
          .map((p) => {
                'productId': p.productId,
                'inId': p.inId,
                'itemName': p.itemName,
                'productImage': p.productImage,
                'price': p.price,
                'crossedPrice': p.crossedPrice,
                'symbol': p.symbol,
                'detailUrl': p.detailUrl,
                'category': p.category,
                'createTime': p.createTime.toIso8601String(),
                'updateTime': p.updateTime.toIso8601String(),
              })
          .toList(),
    };
  }

  Future<void> close() async {
    if (_isInitialized) {
      await _isarService.close();
      _isInitialized = false;
    }
  }
}
